package com.lh.pospi.x_store.ui.purchase;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lh.pospi.x_store.Interface.StatusListener;
import com.lh.pospi.x_store.R;
import com.lh.pospi.x_store.adapter.OrderAdapter;
import com.lh.pospi.x_store.app.MyApp;
import com.lh.pospi.x_store.base.BaseActivity;
import com.lh.pospi.x_store.greendao.BillBeanDao;
import com.lh.pospi.x_store.modle.BillBean;
import com.lh.pospi.x_store.modle.ConditionMsg;
import com.lh.pospi.x_store.modle.OrderBean;
import com.lh.pospi.x_store.utils.BillUtil;
import com.lh.pospi.x_store.utils.Constant;
import com.lh.pospi.x_store.utils.DaoHelper;
import com.lh.pospi.x_store.utils.LoadingUtil;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.vondear.rxtool.RxLogTool;
import com.vondear.rxtool.RxTimeTool;
import com.vondear.rxtool.RxTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogSureCancel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 *
 */
public class PurchaseActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemLongClickListener {
    @BindView(R.id.rv_view)
    RecyclerView recyclerView;
    @BindView(R.id.fab_button)
    FloatingActionButton fab_button;
    @BindView(R.id.date_text)
    QMUIRoundButton date_text;
    @BindView(R.id.spinner)
    Spinner spinner;
    private List<BillBean> billBeans =new ArrayList<>();
    private OrderAdapter orderAdapter;
    private String[] statuses = new String[]{"全部","已上传", "未上传"};
    private String sta = "全部";
    private LoadingUtil util;
    private int count;
    private Thread thread;
    private String billType = Constant.TYPE_D1;

    @Override
    protected int getContentView() {
        return R.layout.activity_pd;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);//注册事件
        billType = getIntent().getStringExtra(Constant.PURCHASE);
        initTitle();
        Button upButton = getTopBar().addRightTextButton("上传", R.mipmap.icon_up);
        upButton.setTextColor(getResources().getColor(R.color.white));
        upButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<BillBean> beanList = new ArrayList<>();
                for (BillBean bean : billBeans) {
                    if (bean.getStatus().equals("0")) {
                        beanList.add(bean);
                    }
                }
                if (beanList.size() > 0) {
                    up(beanList);
                } else {
                    RxToast.warning("没有未上传的订单");
                }

            }
        });
        util = new LoadingUtil(mContext);

        initView();
        initSpinner();


    }

    private void initTitle() {
        switch (billType) {
            case Constant.TYPE_D1:
                getTopBar().setTitle("采购订单");
                break;
            case Constant.TYPE_RK:
                getTopBar().setTitle("采购入库");
                break;
            case Constant.TYPE_TC:
                getTopBar().setTitle("采购退厂");
                break;
        }
    }

    /**
     * @param beans 待上传的订单
     */
    private void up(List<BillBean> beans) {
        util.show("上传中");
        count = beans.size();
        for (BillBean bean : beans) {
            BillUtil.upbill(bean, new StatusListener() {
                @Override
                public void upSuccess(String msg) {
                    RxLogTool.d(msg);
                    reCount();

                }

                @Override
                public void upFailed(String msg) {
                    RxLogTool.d(msg);
                    RxToast.error(msg);
                    reCount();
                }

                @Override
                public void saveSuccess(BillBean bean) {

                }
            });
        }
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!thread.isInterrupted()) {
                    if (count == 0) {
                        break;
                    }
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        break;
                    }
                }
                util.close();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        orderAdapter.notifyDataSetChanged();
                        RxToast.normal("数据上传完成");
                    }
                });
            }
        });
        thread.start();

    }
    private void reCount() {
        synchronized (this) {
            count--;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (thread != null) {
            thread.interrupt();
        }

    }

    /**
     *初始化spinner
     */
    private void initSpinner() {

        ArrayAdapter adapter = new ArrayAdapter(mContext, android.R.layout.simple_list_item_1, statuses);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                sta = statuses[i];
                EventBus.getDefault().post(new ConditionMsg(date_text.getText().toString(), sta, ""));
//                initData(date_text.getText().toString(),sta);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

    }

    private void initView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        orderAdapter = new OrderAdapter(R.layout.item_order, billBeans);
        recyclerView.setAdapter(orderAdapter);

        date_text.setText(RxTimeTool.getCurrentDateTime("yyyy-MM-dd"));

        orderAdapter.setOnItemClickListener(this);
        orderAdapter.setOnItemLongClickListener(this);
    }


    /**
     * 消息订阅，处理数据更新
     * @param conditionMsg 筛选条件实体
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void initData(ConditionMsg conditionMsg) {
        billBeans.clear();
        List<BillBean> beans = DaoHelper.getBills(conditionMsg.getDate(),billType, conditionMsg.getStatus());
        billBeans.addAll(beans);
        orderAdapter.notifyDataSetChanged();
        getTopBar().setSubTitle("共"+beans.size()+"条单据");
    }


    @OnClick({R.id.date_text,R.id.fab_button})
    public void onClick(View v){
        switch (v.getId()) {
            case R.id.date_text:
                showTimer(date_text);
                break;
            case R.id.fab_button:
                Intent intent = new Intent(this, PurchaseDetailActivity.class);
                intent.putExtra(Constant.PURCHASE, billType);
                startActivity(intent);
                break;
        }
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        Intent intent = new Intent(this, PurchaseDetailActivity.class);
        intent.putExtra("bill", billBeans.get(position));
        intent.putExtra(Constant.PURCHASE, billType);
        startActivity(intent);
    }
    public void showTimer(final QMUIRoundButton text) {

        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                text.setText(RxTimeTool.date2String(date,new SimpleDateFormat("yyyy-MM-dd")));
                EventBus.getDefault().post(new ConditionMsg(date_text.getText().toString(), sta, ""));
//                initData(text.getText().toString(),sta);

            }
        }).build();
        pvTime.show();
    }

    @Override
    public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
        DaoHelper.delete(mContext, position, billBeans, orderAdapter);
        return false;
    }


}
